package com.application;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.*;
import util.core.Equation;
import util.core.Format;
import util.core.Molecule;
import util.core.Periodic;
import util.exceptions.UnknownElementException;
import util.tools.stoich.StoiData;
import util.tools.stoich.Stoichiometry;

import java.util.ArrayList;


public class StoichUI extends Activity {
    private ArrayList<StoiData> stData;
    private boolean[] usable;
    private Molecule currentMolecule;
    private Spinner moleculeSpinner, unitSpinner;
    private ArrayList<CharSequence> sequence;
    private String message;
    private String units;
    private Molecule toFind;
    private Stoichiometry toUse;
    private boolean list;
    private static ArrayList<StoiData> temp;

    private View.OnClickListener addListener = new View.OnClickListener() {
        public void onClick(View v) {
            String c = ((EditText) findViewById(R.id.quantity_st)).getText().toString();
            if (!c.equals("") && currentMolecule != null) {
                toFind = null;
                int index;
                if (usable[index = Equation.current.getIndexOf(currentMolecule)]) {
                    try {
                        StoiData temp = new StoiData(currentMolecule, Double.parseDouble(c), "BASE", units);
                        stData.add(temp);
                        ((Spinner) findViewById(R.id.name_st)).setSelection(0);
                    } catch (NumberFormatException e) {
                        message = "<b>An invalid quantity was entered</b><br/>";
                    } finally {
                        populate();
                    }

                    currentMolecule = null;
                    usable[index] = false;
                }
            }
        }
    };

    public AdapterView.OnItemSelectedListener itemClickListener = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            CharSequence o = (CharSequence) moleculeSpinner.getSelectedItem();
            ArrayList<Molecule> m = Equation.current.getLeft();
            for (Molecule molecule : m) {
                if (Html.fromHtml(get(molecule)).toString().equals(o.toString())) {
                    currentMolecule = molecule;
                }
            }
            moleculeSpinner.setSelection(sequence.indexOf(o));
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    };
    public AdapterView.OnItemSelectedListener unitClickListener = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            units = unitSpinner.getSelectedItem().toString();
            populate();
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    };

    public View.OnClickListener menuClickListener = new View.OnClickListener() {
        public void onClick(View view1) {
            if (view1.getId() == R.id.remove_st) {
                toFind = null;
                CharSequence[] temp = new CharSequence[stData.size() + 1];
                for (int i = 0; i < stData.size(); i++) {
                    Molecule m = stData.get(i).getMolecule();
                    String result = get(m);
                    temp[i] = Html.fromHtml(result);
                }
                temp[stData.size()] = "Cancel";

                ListView listView = new ListView(getApplicationContext());
                listView.setAdapter(new CustomAdapter<CharSequence>(getApplicationContext(), android.R.layout.simple_list_item_1, temp));
                setContentView(listView);
                list = true;
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        if (position < stData.size())
                            stData.remove(position);
                        setContentView(R.layout.stoichiometry_layout);
                        init();
                        list = false;
                    }
                });
            } else if (view1.getId() == R.id.get_result_st && stData.size() != 0) {
                final ArrayList<Molecule> right = Equation.current.getRight();
                CharSequence[] temp = new CharSequence[right.size() + 1];
                for (int i = 0; i < right.size(); i++) {
                    Molecule m = right.get(i);
                    String result = get(m);
                    temp[i] = Html.fromHtml(result);
                }
                temp[right.size()] = "Cancel";
                final String text = ((EditText) findViewById(R.id.quantity_st)).getText().toString();
                ListView listView = new ListView(getApplicationContext());
                listView.setAdapter(new CustomAdapter<CharSequence>(getApplicationContext(), android.R.layout.simple_list_item_1, temp));
                setContentView(listView);
                list = true;
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        if (position != right.size()) {
                            Stoichiometry c = new Stoichiometry(Equation.current);
                            try {
                                c.add(stData);
                            } catch (UnknownElementException e) {
                                e.printStackTrace();
                            }
                            toFind = right.get(position);
                            toUse = c;
                        }
                        setContentView(R.layout.stoichiometry_layout);
                        populate();
                        init();
                        list = false;
                        ((EditText) findViewById(R.id.quantity_st)).setText(text);
                    }
                });
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (temp != null) {
            stData = temp;
            temp = null;
        } else
            stData = new ArrayList<StoiData>();

        setContentView(R.layout.stoichiometry_layout);
        Periodic.initialize(getApplicationContext());
        init();
    }

    private void initUsable(int size) {
        usable = new boolean[size];
        for (int i = 0; i < usable.length; i++) {
            usable[i] = true;
        }
    }


    public void populate() {
        String result = "<html><small><p>" + message + "<br/><b>Current Quantities:</b><br/>";
        message = "";
        if (stData.size() == 0)
            result += "none";
        else {
            boolean first = true;
            for (StoiData st : stData) {
                if (!first)
                    result += " , ";
                else
                    first = false;
                result += st.toString();
            }
        }

        Stoichiometry stoichiometry = new Stoichiometry(Equation.current);
        try {
            stoichiometry.add(stData);
        } catch (UnknownElementException e) {
            e.printStackTrace();
        }
        result += "</p><p><b> Limiting Reactants: </b><br/>";
        result += stoichiometry.getLimiting();

        result += "</p>";
        if (toFind != null) {
            result += toUse.getResult(toFind, units.charAt(0));
        }
        result += "</html>";
        ((TextView) findViewById(R.id.result_st)).setText(Html.fromHtml(result));
    }

    private String get(Molecule m) {
        return "<html><p>" + Format.toFormattedString(m) + "</p></small></html>";
    }


    public void init() {
        message = "";
        moleculeSpinner = (Spinner) (findViewById(R.id.name_st));
        sequence = new ArrayList<CharSequence>();
        ArrayList<Molecule> left = Equation.current.getLeft();
        for (int i1 = 0, leftSize = left.size(); i1 < leftSize; i1++) {
            Molecule m = left.get(i1);
            String result = get(m);
            sequence.add(Html.fromHtml(result));
        }
        CharSequence[] s = new CharSequence[sequence.size()];
        CustomAdapter<CharSequence> adapter = new CustomAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_item, sequence.toArray(s));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        moleculeSpinner.setAdapter(adapter);
        moleculeSpinner.setOnItemSelectedListener(itemClickListener);
        moleculeSpinner.setPromptId(R.string.molecule_prompt);

        unitSpinner = (Spinner) findViewById(R.id.units_st);
        ArrayAdapter<? extends CharSequence> c = ArrayAdapter.createFromResource(this, R.array.units, android.R.layout.simple_spinner_item);
        c.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        unitSpinner.setAdapter(c);
        unitSpinner.setOnItemSelectedListener(unitClickListener);
        if (units == null)
            units = "g";
        else {
            if (units.equals("L (STP)")) {
                unitSpinner.setSelection(1);
            } else if (units.equals("mol")) {
                unitSpinner.setSelection(2);
            }
        }

        findViewById(R.id.add_st).setOnClickListener(addListener);
        findViewById(R.id.remove_st).setOnClickListener(menuClickListener);
        findViewById(R.id.get_result_st).setOnClickListener(menuClickListener);
        initUsable(Equation.current.getLeft().size());
        populate();
    }

    public void onBackPressed() {
        if (list) {
            setContentView(R.layout.stoichiometry_layout);
            init();
        } else
            finish();
    }

    public void onConfigurationChanged(Configuration newConfiguration) {
        temp = stData;
        super.onConfigurationChanged(newConfiguration);
    }


}

